
<template>
  <div class="page" :style="pageStyle">
    <div id="preview" :style="previewStyle">
      <template v-for="(card) in cards" :key="card._id">
        <!-- <div v-if="card.interactive.enterAnimation.type" :style="getEnterAnimationStyle(card.interactive)">
          <div class="card" :style="getShapeStyle(card.style, card.interactive)">
            <component :comData="card.comData" :is="card.component" :initProp="card.cardJson.initProp" />
          </div>
        </div> -->
        <div class="card" :class="card.class" :style="getShapeStyle(card.style, card.enterAnimation)">
          <component :comData="card.comData" :is="card.component" :initProp="card.cardJson.initProp" />
        </div>
      </template>

    </div>
  </div>
</template>
<script setup>
import { defineAsyncComponent, ref, onMounted, computed } from 'vue'
import { fillStyle } from "../editor/utils/utils"
import { addExternalEle, getComData } from '/@/utils/common'
import '/@/assets/animate.css'
import { queryPage } from './request/page'
import { login } from './request/index'


function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]); return null;
}


const groupCom = defineAsyncComponent(() => {
  return import('../../components/group.vue')
})

// 卡片公共样式配置
const getShapeStyle = (style, enterAnimation) => {
  const result = fillStyle(style, ['top', 'left', 'width', 'height', 'rotate'])
  return {
    ...result,
    ...enterAnimation
  }

}
// 目录树
const cardsHandler = (cards) => {
  for (let i = 0, l = cards.length; i < l; i++) {
    const card = cards[i]
    card.component = card.group ? groupCom : defineAsyncComponent(() => {
      return new Promise(async r => {
        const VueDemo = await import(/* @vite-ignore */`${card.url} `)
        r(VueDemo)
      })
    })
    getComData(card.cardJson).then(data => {
      card.comData = data
    })
    card.cardJson.initProp.cards && cardsHandler(card.cardJson.initProp.cards)
  }
}

const getEnterAnimationStyle = (interactive) => {
  const {
    type,
    timingFunction,
    direction,
    duration,
    delay
  } = interactive.enterAnimation
  return {
    'animation-name': type + direction,
    'animation-duration': duration + 'ms',
    'animation-timing-function': timingFunction,
    'animation-delay': delay + 'ms'
  }
}
let cardStore

const cards = ref([])

// 缩放布局
const scalePagesStyle = ref({})
const setScalePage = () => {
  const { width, height } = cardStore.editor
  const getScaleStyle = () => {
    const widthScale = innerWidth / width
    const heightScale = innerHeight / height
    const s = Math.min(widthScale, heightScale)
    scalePagesStyle.value = widthScale > heightScale ? {
      top: 0,
      transform: `scale(${s})`,
      left: (innerWidth - width * heightScale) / 2 + 'px'
    } : {
      left: 0,
      transform: `scale(${s})`,
      top: (innerHeight - height * widthScale) / 2 + 'px'
    }
  }
  getScaleStyle()
  window.addEventListener('resize', getScaleStyle)
}





// 设置画布样式
const getCanvalStyle = () => {
  const { width, height, backgroundColor } = cardStore.editor
  return {
    width: width + 'px',
    height: height + 'px',
    backgroundColor
  }
}

const canvasStyle = ref({})

const previewStyle = computed(() => {
  return {
    ...canvasStyle.value,
    ...scalePagesStyle.value
  }
})

// 设置页面样式

// flex布局
const layoutMap = {
  1: () => {
    return `display: flex; align-items: center;justify-content: center;`
  },
  2: () => {
    return `display: flex; justify-content: center;`
  },
  3: () => {
    return `display: flex; align-items: center;`
  },
}
const getPageStyle = () => {
  const { layout, padding } = cardStore
  const paddingStyle = 'padding:' + padding.join('px ') + 'px'
  const style = layoutMap[layout] ? layoutMap[layout]() : ''

  return `
    ${style}
    ${paddingStyle};
    ${layout === '4' ? ';overflow:hidden' : ''}
  `
}
const pageStyle = ref({})

onMounted(async () => {
  // 获取页面内容
  const pid = GetQueryString('pid')
  try {
    if (pid) {
      await login()
      const res = await queryPage(pid)
      res[0] && (cardStore = res[0].content)
    } else {
      cardStore = JSON.parse(sessionStorage.getItem('pageStore'))
    }
  } catch (error) {
    cardStore = { cards: [] }
  }
  console.log(cardStore)

  if (cardStore.layouts) {
    const layout = cardStore.layouts.find(item => {
      return item.min < innerWidth && item.max > innerWidth
    })
    if (layout) {
      layout.type === 'link' && (window.location.href = layout.type)
      cardStore.layout = layout.layout
      cardStore.padding = layout.padding
    }
  }

  // 画布样式
  canvasStyle.value = getCanvalStyle()

  //  页面样式
  pageStyle.value = getPageStyle()

  // 加载外部文件
  const externals = cardStore.editor?.externals || []
  await addExternalEle(externals)
  cardsHandler(cardStore.cards)
  cards.value = cardStore.cards

  // 缩放布局设置
  const { layout } = cardStore
  layout === '4' && setScalePage()

  // 设置页面名称
  document.querySelector('title').innerText = cardStore.name
  document.addEventListener('animationend', function (event) {
    // 当动画结束时触发该函数
    event.target.className = 'card'
  });
})

</script>

<style lang="less" scoped>
#preview {
  position: relative;
  overflow: hidden;
  transform-origin: 0 0;
}

.card {
  position: absolute
}
</style>
<style>
.page {
  height: 100vh;
  width: 100vw;
  background-color: #f5f5f5;
  overflow: auto;
}

@keyframes slider-inleft {
  0% {
    transform: translateX(-100%);
  }

  100% {
    transform: translateX(0);
  }
}
</style>
